package com.masterclient.app.modules.search;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.eoner.baselib.utils.sp.SPUtils;
import com.eoner.common.config.Config;
import com.eoner.managerlibrary.router.AroutePath;
import com.masterclient.app.BaseActivity;
import com.masterclient.app.R;
import com.masterclient.app.base.ConfirmDialog;
import com.masterclient.app.base.FragmentHostActivity;
import com.masterclient.app.httpservice.ApiService;
import com.masterclient.app.modules.search.adapter.SearchAssociateAdapter;
import com.masterclient.app.modules.search.beans.SearchAssociateBean;
import com.masterclient.app.modules.search.contract.SearchAssociateContract;
import com.masterclient.app.modules.search.contract.SearchAssociatePresenter;
import com.masterclient.app.widget.FlowLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnEditorAction;
import io.reactivex.disposables.Disposable;

import static com.eoner.baselibrary.utils.ScreenUtils.dp2px;
import static com.eoner.common.config.Config.SEARCH_HISTORY;
import static com.masterclient.app.R.id.search_history;

/**
 * 作者：sean
 * 创建时间：2017/6/22 10:35
 * 功能说明：搜索记录页面
 */

public class SearchHistoryActivity extends BaseActivity<SearchAssociatePresenter> implements SearchAssociateContract.View {

    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.tv_cancle)
    TextView tvCancle;
    @BindView(R.id.rl_search_main)
    RelativeLayout rlSearchMain;
    @BindView(R.id.rl_delete_history)
    RelativeLayout rlDeleteHistory;
    @BindView(R.id.edit_ll)
    LinearLayout llEdit;
    @BindView(R.id.flow_history)
    FlowLayout flowHistory;
    @BindView(search_history)
    LinearLayout searchHistory;
    @BindView(R.id.et_search_text)
    EditText etSearchText;
    @BindView(R.id.search_result_clear)
    FrameLayout searchClear;

    private List<String> historyQueue;
    private Gson gson;
    private String history;
    private ApiService apiService;
    private String[] defaultHints = {"丝绸","扇子","茶叶","糕点"};
    private ConfirmDialog deleteDialog;
    private boolean isShow;
    private int num;
    private boolean isDelete;

    String hint_word;
    private SearchAssociateAdapter associateAdapter;
    public Disposable disposable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        gson = new Gson();
        isDelete = false;
        apiService = new ApiService();
        Random random = new Random();
        isShow = false;
        hint_word = getIntent().getStringExtra("hint_word");
        if(!TextUtils.isEmpty(hint_word)){
            etSearchText.setHint(hint_word);
        }
        num = 3;
        showSearchHistory();

        etSearchText.postDelayed(new Runnable() {
            @Override
            public void run() {
                showSoftInput(etSearchText);
            }
        },200);

        etSearchText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                searchClear.setVisibility(charSequence.toString().length()>0?View.VISIBLE:View.INVISIBLE);
                if (etSearchText.getText().toString().length()>0){
                    if (disposable != null && !disposable.isDisposed()) disposable.dispose();
                    disposable = mPresenter.searchAssociate(etSearchText.getText().toString());
                }else {
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

    }


    @Override
    protected void onResume() {
        super.onResume();
        if (etSearchText != null && etSearchText.getText().toString().length()>0){
            etSearchText.setSelection(etSearchText.getText().toString().length());
            showSoftInput(etSearchText);
        }
    }

    @Override
    protected void onRestart() {
        num = 3;
        showSearchHistory();
        super.onRestart();
    }

    private void showSearchHistory() {
        history = SPUtils.getInstance().getString(SEARCH_HISTORY);
        if(TextUtils.isEmpty(history)){
            searchHistory.setVisibility(View.GONE);
        }else {
            historyQueue = gson.fromJson(history,new TypeToken<ArrayList<String>>() {
            }.getType());
            flowHistory.removeAllViews();
            int size = historyQueue.size();
            for(int i = (size-1);i>=0;i--){
                String s = historyQueue.get(i);
                LinearLayout view = (LinearLayout) View.inflate(SearchHistoryActivity.this, R.layout.text_search, null);
                TextView t = view.findViewById(R.id.name);
                ImageView delete = view.findViewById(R.id.delete);
                delete.setVisibility(isDelete?View.VISIBLE:View.GONE);
                t.setText(s);
                view.setOnClickListener((v)-> {
                    Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.SEARCH_RESULT_FRAGMENT)
                            .withString("keyword", s)
                            .navigation();
                    FragmentHostActivity.openFragment(this,fragment);
                });
                delete.setOnClickListener(((v)->{
                    historyQueue.remove(s);
                    flowHistory.removeView(view);
                    SPUtils.getInstance().put(SEARCH_HISTORY,gson.toJson(historyQueue));
                }));
                ViewGroup.MarginLayoutParams lp = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                lp.setMargins(dp2px(5), dp2px(16), dp2px(5), 0);
                flowHistory.addView(view,lp);
            }
            flowHistory.specifyLines(num);
        }
    }

    @OnEditorAction(R.id.et_search_text) boolean onEditSearch(TextView tv, int imeAction, KeyEvent event){
        if (imeAction == EditorInfo.IME_ACTION_SEARCH) {
            // 当按了搜索之后关闭软键盘
            String search = tv.getText().toString().trim();
            ((InputMethodManager) tv.getContext().getSystemService(
                    Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                    getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
            if(TextUtils.isEmpty(search)){
                showToast("搜索内容不能为空");
            }else {
                search(search,false);
            }
            return true;
        }
        return false;
    }

    @Override
    protected void onPause() {
        hideSoftInput(etSearchText);
        super.onPause();
    }

    private void search(String search,boolean isRem) {
        if(historyQueue == null){
            historyQueue = new ArrayList<>();
            historyQueue.add(search);
            SPUtils.getInstance().put(SEARCH_HISTORY,gson.toJson(historyQueue));
        }else {
            if(historyQueue.contains(search)){
                historyQueue.remove(search);
                historyQueue.add(search);
                SPUtils.getInstance().put(SEARCH_HISTORY,gson.toJson(historyQueue));
            }else {
                historyQueue.add(search);
                SPUtils.getInstance().put(SEARCH_HISTORY,gson.toJson(historyQueue));
            }
        }
        Fragment fragment = (Fragment) ARouter.getInstance().build(AroutePath.SEARCH_RESULT_FRAGMENT)
                .withString("keyword", search)
                .navigation();
        FragmentHostActivity.openFragment(this,fragment);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (resultCode){
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.tv_cancle,R.id.view_back}) void back(View v){
        switch (v.getId()){
            case R.id.tv_cancle:
                String search = etSearchText.getText().toString().trim();
                ((InputMethodManager) etSearchText.getContext().getSystemService(
                        Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
                        getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
                if(TextUtils.isEmpty(search)){
                    showToast("搜索内容不能为空");
                }else {
                    search(search,false);
                }
                break;
            case R.id.view_back:
                finish();
                break;
        }
    }

    @OnClick({R.id.search_result_clear,R.id.rl_delete_history,R.id.complete,R.id.clear_history,R.id.tv_cancle})void onClick(View v){
        switch (v.getId()){
            case R.id.search_result_clear:
                etSearchText.setText("");
                break;
            case R.id.clear_history:
                if (deleteDialog == null){
                    deleteDialog = new ConfirmDialog(mContext,"是否清空所有搜索记录？","取消","确定");
                    deleteDialog.setOnChooseListerner(new ConfirmDialog.OnChooseListerner() {
                        @Override
                        public void cancel() {
                            deleteDialog.dismiss();
                        }
                        @Override
                        public void confirm() {
                            llEdit.setVisibility(View.GONE);
                            rlDeleteHistory.setVisibility(View.VISIBLE);
                            SPUtils.getInstance().put(Config.SEARCH_HISTORY,"");
                            historyQueue = null;
                            showSearchHistory();
                            deleteDialog.dismiss();
                        }
                    });
                }
                deleteDialog.show();
                break;
            case R.id.rl_delete_history:
                llEdit.setVisibility(View.VISIBLE);
                rlDeleteHistory.setVisibility(View.INVISIBLE);
                isDelete = !isDelete;
                num = Integer.MAX_VALUE;
                showSearchHistory();
                break;
            case R.id.complete:
                llEdit.setVisibility(View.GONE);
                rlDeleteHistory.setVisibility(View.VISIBLE);
                isDelete = !isDelete;
                showSearchHistory();
                break;
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
        if(historyQueue == null || historyQueue.isEmpty()){
            searchHistory.setVisibility(View.GONE);
        }else {
            searchHistory.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void loadFailed(String msg) {

    }

    @Override
    public void showSearchAssociate(String keyword, List<SearchAssociateBean> beans) {
        if (etSearchText.getText().toString().length()>0&&beans!=null&&beans.size()>0) {
            if (etSearchText.getText().toString().equals(keyword)) {
                associateAdapter.setNewData(beans);
            }
        }else {
        }
    }
}
